<?php
namespace app\api\controller;

use think\Request;
use think\Config;
use app\api\model\User;
use app\api\model\UserInfo;

class Auth extends Base
{
	public function _initialize(Request $request = null)
    {
        parent::_initialize($request);
         $token = request()->header('token');
//        $token = '71dd48404ece2c2d425f3269316d7d0155016851f3b4d23fd8';
        //TODO：前端传不了 header 的情况
        if (empty($token)) {
            $token = request()->param('token');
        }
        $this->user = User::alias('u')
            ->where('u.token', $token)
            ->join('jk_user_informations m', 'u.user_id = m.user_id', 'LEFT')
            ->join('jk_user_authentications a', 'a.user_id = u.user_id', 'LEFT')
            ->field('u.user_id, u.username, u.wechat_openid, u.session_key, u.token, m.nickname, a.status')
            ->find();

        $login_end_time = \think\Db::table('jk_loginrecordings')
            ->where('user_id', $this->user->user_id)
            ->order('create_at DESC')
            ->field('create_at')
            ->value('create_at');  //最后登录时间

        //用户信息为空，或者token过期
        if (empty($this->user) || ($login_end_time + Config::get('web.token_overdue')) < time()) {
            $res = array(
                'code' => 1,
                'message' => 'login please',
                'data' => []
            );
            echo json_encode($res, true);
            exit;
        }
    }
}